from django.shortcuts import render,HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from captcha.image import ImageCaptcha
import jwt,redis,random
import string,re
from zbj.my_redis import r
from zbj.models import *
from zbj.sms_code import sms_code
# 生成图片验证码的接口
class Img_code(APIView):
    def get(self,request):
        uuid=request.query_params.get("uuid")
        img_code="".join(random.sample(string.digits+string.ascii_letters,4))
        cap=ImageCaptcha()
        img=cap.generate(img_code)
        r.set_str(uuid,img_code,120)
        return HttpResponse(img,content_type="image/png")

# 生成短信验证码
class Sms_code(APIView):
    def get(self,request):
        uuid = request.query_params.get("uuid")
        imgcode=request.query_params.get("imgcode")
        mobile=request.query_params.get("mobile")
        if not all([uuid,mobile,imgcode]):
            return Response({"code":400,'msg':'字段不完整'})
        if not re.findall(r"1[3-9]\w{9}$",mobile):
            return Response({"code":400,'msg':'手机号格式错误'})
        mob=r.get_str("code"+mobile)
        if mob:
            return Response({"code":400,'msg':'请勿重复操作'})
        res=r.get_str(uuid)
        if res:
            res=res.decode()
            if res.lower()!=imgcode.lower():
                return Response({"code":400,'msg':'图片验证码错误'})
            sms_code(mobile)
            r.del_str(uuid)
            return Response({"code":200,'msg':'发送成功，请注意查收'})
        else:
            return Response({"code":400,'msg':'图片验证码过期，请刷新重试'})

